/**
 * 
app.get('/books', service.allBooks);
app.post('/book', service.addBook);
app.get('/book/:id', service.getBookById);
app.put('/book', service.editBook);
app.delete('/book/:id', service.deleteBook);
 */

const db = require('./db');

exports.allBooks = (req, resp) => {
    let sql = "SELECT * FROM t_book";
    db.base(sql, null, (err, results, fields)=>{
        if (err) {
            resp.json({status:'failure',msg:'系统错误，请联系管理员'});
            return;
        }
        resp.json(results);
    });
}

exports.getBookById = (req, resp) => {
    let id = req.params.id;
    let sql = "SELECT * FROM t_book WHERE id = ?";
    db.base(sql, id, (err, results, fields)=>{
        if (err) {
            resp.json({status:'failure',msg:'系统错误，请联系管理员'});
            return;
        }
        resp.json(results[0]);
    });
}

// 添加图书（保存数据）
exports.addBook = (req,resp) => {
    let info = req.body;
    //console.log(info);
    let book = Object.assign({}, info);

    let sql = "INSERT INTO t_book SET ?";
    db.base(sql, book, (err, results, fields)=>{
        if (err) {
            //console.log(err.stack);
            resp.json({status:'failure',msg:'系统错误，请联系管理员'});
            return;
        }
        if (results && results.affectedRows === 1) {
            resp.json({status:'success',msg:'添加图书成功！'});
        } else {
            resp.json({status:'failure',msg:'系统错误，请联系管理员'});
        }
    });
}

exports.editBook = (req, resp) => {

    let book = req.body;
    let dataArr = [];
    dataArr.push(book.name);
    dataArr.push(book.author);
    dataArr.push(book.category);
    dataArr.push(book.description);
    dataArr.push(book.id);

    // 这里不能这样写,要添加配置。但那个配置可能影响“全局”，如果只是“局部”生效，还可以用一下。
    // let sql = "UPDATE t_book SET name = :name, author = :author, category = :category, description = :description where id = :id";
    let sql = "UPDATE t_book SET name = ?, author = ?, category = ?, description = ? where id = ?";
    db.base(sql, dataArr, (err, results, fields)=>{
        if (err) {
            //console.log(err.stack);
            resp.json({status:'failure',msg:'系统错误，请联系管理员'});
            return;
        }
        if (results && results.affectedRows === 1) {
            resp.json({status:'success',msg:'图书修改成功！'});
        } else {
            resp.json({status:'failure',msg:'系统错误，请联系管理员'});
        }
    });
}

exports.deleteBook = (req, resp) => {
    let _id = req.params.id;

    let sql = "DELETE FROM t_book WHERE id=?";
    db.base(sql, _id, (err, results, fields)=>{
        if (err) {
            resp.json({status:'failure',msg:'系统错误，请联系管理员'});
            return;
        }
        if (results && results.affectedRows === 1) {
            resp.json({status:'success',msg:'删除图书成功！'});
        } else {
            resp.json({status:'failure',msg:'系统错误，请联系管理员'});
        }
    });
}
